package com.ias.agdis_r.view.control;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
//import android.support.v4.content.ContextCompat;
import androidx.core.content.ContextCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;

import com.ias.agdis_r.R;

/***
 * @author huzedong
 * 清除editortext
 * **/
public class EditorTextClear extends EditText implements OnFocusChangeListener {
	private Drawable imgEnable;

	private Context context;

	public EditorTextClear(Context context) {
		super(context);
		this.context = context;
		init();
	}

	public EditorTextClear(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		init();
	}

	public EditorTextClear(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
	}

	private void init() {
		imgEnable = ContextCompat.getDrawable(context, R.drawable.clear);
		imgEnable.setBounds(0, 0, imgEnable.getIntrinsicWidth(), imgEnable.getIntrinsicHeight());
		addTextChangedListener(new TextWatcher() {

			private long millsCache;

			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			public void afterTextChanged(final Editable s) {
				setDrawable();

				// 输入内容输入完成回调，防止连续输入
				if (completeListener == null) {
					return;
				}
				long currentTimeMillis = System.currentTimeMillis();
				isFilter = currentTimeMillis - millsCache > delayTime;
				if (timer != null) {
					timer.cancel();
					timer.start();
				} else {
					timer = new EditorTextClear.MyInputCountDown(delayTime, 1);
				}
				postDelayed(new Runnable() {
					@Override
					public void run() {
						if (isFilter) {
							callInputCompleted(s);
						}
					}
				}, delayTime + 100);

				millsCache = currentTimeMillis;
			}

		});

		setDrawable();
	}

	/** 输入完成间隔时间 */
	private long delayTime = 300;
	private boolean isFilter = false;
	private EditorTextClear.EditInputCompleteListener completeListener;
	private CountDownTimer timer;

	public void addEditInputCompleteListener( EditorTextClear.EditInputCompleteListener completeListener) {
		this.completeListener = completeListener;
	}

	public interface EditInputCompleteListener {
		void inputCompleted(CharSequence charSequence);
	}

	private void callInputCompleted(CharSequence charSequence) {
		if (completeListener != null) {
			completeListener.inputCompleted(charSequence);
		}
	}

	/**
	 * 连续输入计时器
	 */
	private class MyInputCountDown extends CountDownTimer {

		/**
		 * @param millisInFuture    The number of millis in the future from the call
		 *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
		 *                          is called.
		 * @param countDownInterval The interval along the way to receive
		 *                          {@link #onTick(long)} callbacks.
		 */
		public MyInputCountDown(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {

		}

		@Override
		public void onFinish() {
			isFilter = true;
		}
	}

	private void setDrawable() {
		if (length() == 0) {
			setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		} else {
			setCompoundDrawablesWithIntrinsicBounds(null, null, imgEnable, null);
			setCompoundDrawablePadding((int) getTextSize() / 2);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (imgEnable != null && event.getAction() == MotionEvent.ACTION_UP) {
			int x = (int) event.getX();
//			boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight())) && (x < (getWidth() - getPaddingRight()));
			boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight())) && (x < getWidth());
			Rect rect = imgEnable.getBounds();
			int height = rect.height();
			int y = (int) event.getY();
			int distance = (getHeight() - height) / 2;
//			boolean isInnerHeight = (y > distance) && (y < (distance + height));
			boolean isInnerHeight = (y > (getHeight() - height - distance * 2)) && (y < getHeight());
			// 修改isInnerWidth 和 isInnerHeight 增大清除按钮点击区域

			if (isInnerWidth && isInnerHeight && this.isEnabled()) {
				setText("");
			}

		}

		return super.onTouchEvent(event);
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();

	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (hasFocus) {
			setDrawable();
		} else {
			setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		}
	}

	@Override
	public void setText(CharSequence text, BufferType type) {
		super.setText(text, type);
		this.setSelection(text.length());
	}
}
